class Solution(object):
    def nextGreaterElements(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        n = len(nums)
        out = [-1] * n
        stack = [0]
        for i in range(1, n):
            while stack and nums[i] > nums[stack[-1]]:
                out[stack[-1]] = i
                stack.pop()
            stack.append(i)

        for i in range(n):
            while stack and nums[i] > nums[stack[-1]]:
                out[stack[-1]] = i
                stack.pop()
        for i in range(n):
            if out[i] >= 0:
                out[i] = nums[out[i]]
        return out




data = Solution()
nums = [1, 2, 1]
print(data.nextGreaterElements(nums))
